﻿using System;
using System.Security.Principal;
using System.Diagnostics;
using System.Threading;

namespace negoserverjni
{
    public class Translation
    {
        internal static TraceSource log = new TraceSource("Translation");
        public static byte[] TranslateNameToSid(string name)
        {
            if (name == null) return null;
            name = name.Trim();
            if (name.Length == 0) return null;
            NTAccount account = new NTAccount(name);
            SecurityIdentifier si;
            try
            {
                si = (SecurityIdentifier)account.Translate(typeof(SecurityIdentifier));
            }
            catch (Exception e)
            {
                log.TraceEvent(TraceEventType.Verbose,Thread.CurrentThread.ManagedThreadId, e.GetType() + ":" + e.Message);
                return null;
            }
            byte[] binarysi = new byte[si.BinaryLength];

            si.GetBinaryForm(binarysi, 0);
            return binarysi;
        }

        public static string TranslateSidIntoName(byte[] sidInbytes)
        {
            string Name = null;
            try
            {
                SecurityIdentifier si = new SecurityIdentifier(sidInbytes, 0);
                NTAccount account = (NTAccount)si.Translate(typeof(NTAccount));
                Name = account.ToString();
            }
            catch(Exception e)
            {
                log.TraceEvent(TraceEventType.Verbose, Thread.CurrentThread.ManagedThreadId, e.GetType() + ":" + e.Message);
                Name = null;
            }
            return Name;
        }

        static public byte[][] TranslateNamesToSids(string[] names)
        {
            if (names == null || names.Length == 0) return null;
            byte[][] binarysids = new byte[names.Length][];
            for (int i = 0; i < names.Length; i++)
            {
                binarysids[i] = TranslateNameToSid(names[i]);
            }
            return binarysids;
        }
    }

}
